package org.bit.lesson07;

import java.util.concurrent.TimeUnit;

/**
 * 创建生产者消费者模型
 */
public class Demo_703 {
    public static void main(String[] args) {
        // 定义阻塞队列
        MyBlockingQueue queue = new MyBlockingQueue(100);

        // 创建生产者线程
        Thread producer = new Thread(() -> {
            int num = 0;
            // 使用循环不同向队列中添加元素，直到容量占满
            while (true) {
                try {
                    queue.put(num);
                    System.out.println("生产了元素：" + num);
                    num++;
                    TimeUnit.MICROSECONDS.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        // 启动线程
        producer.start();

        // 创建消费者线程
        Thread consumer = new Thread(() -> {
            while (true) {
                try {
                    Integer value = queue.take();
                    System.out.println("消费了元素：" + value);
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        // 启动线程
        consumer.start();
    }
}
